package cn.js189.uqc.util;

import cn.js189.common.constants.JtdqContants;
import cn.js189.uqc.domain.check.CheckParam;
import cn.js189.uqc.domain.invoice.InterceptParam;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
public class JtdqSysUtil {
	
	public static String checkPurchaseRestrictions(JSONObject body,String url){
		try {
			String phone = body.getString("phone");
			String idCardNo = body.getString("idCardNo");
			JSONObject reqJson = new JSONObject();
			JSONObject head = new JSONObject();
			JSONObject biz = new JSONObject();
			biz.put("sendCusmobile",phone);
			biz.put("idcardno",idCardNo);
			
			head.put("sysCode", JtdqContants.AST_SYS_CODE);
			head.put("appCode", JtdqContants.AST_APPCODE);
			String sendTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
			head.put("reqTime", sendTime);
			head.put("method", JtdqContants.AST_METHOD);
			head.put("version", JtdqContants.AST_VERSION_PORT);
			head.put("attach", "hello,189.cn");
			String reqTime = new SimpleDateFormat("yyyyMMddHHmm").format(new Date());
			//报文流水号，请求方生成。规则：系统编码(6位)+应用编码(6位)+时间(yymmddhhmm,10位)+GUID(32位)，共54位
			String transactionId = JtdqContants.AST_SYS_CODE + JtdqContants.AST_APPCODE + reqTime + UUID.randomUUID().toString().replace("-", "");
			//消息签名 格式：MD5 32位小写(系统编码+应用编码)
			String sign = MD5Utils.mD5( JtdqContants.AST_SYS_CODE + JtdqContants.AST_APPCODE);
			head.put("transactionId", transactionId);
			head.put("sign", sign);
			
			reqJson.put("head",head);
			reqJson.put("biz",biz);
			CheckParam checkParam = new CheckParam();
			String xAuthDq = checkParam.generateXAuthDqRoot(reqJson.toString(),JtdqContants.PR_METHOD);
			Map<String,String> headMap = new HashMap<>();
			headMap.put("Content-Type", "application/json;charset=UTF-8");
			headMap.put("x-auth-dq", xAuthDq);
			log.info("调用集团电渠限购策略校验接口，入参:{}",reqJson);
			String res = HttpClientUtils.sendPostWithHead(url, reqJson.toString(),false, headMap);
			log.info("调用集团电渠限购策略校验接口，出参:{}",res);
			return res;
		} catch (Exception e) {
			log.error("调用集团电渠限购策略校验接口报错：{}",e.getMessage());
			return null;
		}
	}
	
	public static String checkRcBlackList(String url,JSONObject body){
		try {
			String mob = body.getString("mob");
			String card = body.getString("card");
			String goodsId = body.getString("goodsId");
			String reportId = body.getString("reportId");
			String equipment = body.getString("equipment");
			String cps = body.getString("cps");
			String provinceCode = body.getString("provinceCode");
			String cityCode = body.getString("cityCode");
			String countyCode = body.getString("countyCode");
			String address = URLEncoder.encode(body.getString("address"),"UTF-8");
			
			JSONObject reqJson = new JSONObject();
			reqJson.put("mob", mob);
			reqJson.put("card", card);
			reqJson.put("goodsId", goodsId);
			reqJson.put("reportId", reportId);
			reqJson.put("equipment", equipment);
			reqJson.put("cps", cps);
			reqJson.put("provinceCode", provinceCode);
			reqJson.put("cityCode", cityCode);
			reqJson.put("countyCode", countyCode);
			reqJson.put("address", address);
			
			String reqStr = getReq(reqJson);
			InterceptParam interceptParam = new InterceptParam();
			String xAuthDq = interceptParam.generateXAuthDqRoot(reqStr,JtdqContants.RC_CHECK_METHOD);
			Map<String,String> headMap = new HashMap<>();
			headMap.put("Content-Type", "application/json;charset=UTF-8");
			headMap.put("x-auth-dq", xAuthDq);
			log.info("调用集团电渠拦截校验接口，入参:{}",reqJson);
			String res = HttpClientUtils.sendGet(url, headMap);
			log.info("调用集团电渠拦截校验接口，出参:{}",res);
			return res;
		} catch (Exception e) {
			log.error("调用集团电渠拦截校验接口报错：{}",e.getMessage());
			return null;
		}
	}
	
	public static String getGMPropertyRecords(JSONObject body,String url) {
		try {
			String accNumber = body.getString("accNbr");
			String vipCode = body.getString("vipCode");
			JSONObject requestBodyJSON = new JSONObject();
			requestBodyJSON.put("accNumber", accNumber);
			requestBodyJSON.put("vipCode", vipCode);
			String requestBody = requestBodyJSON.toString();
			String interfaceId = "I10003";
			String uri ="/osa/interface";
			String xAuthDq = getXAuthDq(requestBody,interfaceId,uri);
			Map<String,String> headMap = new HashMap<>();
			headMap.put("Content-Type", "application/json;charset=UTF-8");
			headMap.put("x-auth-dq", xAuthDq);
			return HttpClientUtils.sendPostWithHead(url, requestBody,false, headMap);
		} catch (Exception e) {
			return null;
		}
	}
	
	private static String getXAuthDq(String requestBody,String interfaceId,String uri){
		String reqTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		String uuid = UUID.randomUUID().toString().replace("-", "");
		String transactionId = JtdqContants.AST_SYS_CODE+JtdqContants.APP_CODE+reqTime+uuid;
		String sign = JtdqContants.SECRET_VERSION+MD5Utils.mD5(transactionId+JtdqContants.JTDQ_SECRET+uri+requestBody);
		return transactionId+";"+JtdqContants.SYS_CODE+";"+JtdqContants.APP_CODE+";"+interfaceId+";"+JtdqContants.VERSION+";"+sign+";"+reqTime;
	}
	
	/**
	 * 参数拼接
	 * @param params 参数
	 * @return 结果
	 */
	private static String getReq(JSONObject params){
		List<String> names = new ArrayList<>(params.keySet());
		names.sort(String::compareToIgnoreCase);
		StringBuilder strReq = new StringBuilder();
		
		strReq.append("?");
		int i=0;
		for(String k : names){
			if (params.get(k)!=null) {
				if(i == 0){
					strReq.append(k).append("=");
				}
				else{
					strReq.append("&").append(k).append("=");
				}
				
				strReq.append(params.get(k));
				i++;
			}
		}
		return strReq.toString();
		
	}

}
